#ifndef URCONTROLQT_HPP
#define URCONTROLQT_HPP
#include <QTcpSocket>
#include "urcontrolqtserver.h"
#include <iostream>

class URControlQT
{
protected:
    static bool startclient(uint16_t portno, const char *hostname, const char *buffer)
    {
        QTcpSocket socket;
        socket.connectToHost(QString(hostname),portno);
        if(socket.waitForConnected())
        {
            socket.write(buffer);
            socket.waitForBytesWritten(-1);
            socket.waitForReadyRead(-1);
            socket.disconnectFromHost();
            return true;
        }
        std::cout<<"connectToHost "<<hostname<<":"<<portno<<" error\n";
        return false;
    }

    //https://www.universal-robots.com/how-tos-and-faqs/how-to/ur-how-tos/modbus-server-16377/
    static bool ReadModbusRegister(const char *ipUR, unsigned char registerNum, unsigned short startAddress, short *registerValue, uint16_t modbusPort=502)
    {
        QByteArray cmd(12,0);
        cmd[0]=0;
        cmd[1]=1;
        cmd[2]=0;
        cmd[3]=0;
        cmd[4]=0;
        cmd[5]=6;
        cmd[6]=0;
        cmd[7]=3;
        cmd[8]=startAddress>>8;
        cmd[9]=startAddress;
        cmd[10]=0;
        cmd[11]=registerNum;


        QTcpSocket tcpSocket;
        tcpSocket.connectToHost(QString(ipUR),modbusPort);
        if(tcpSocket.waitForConnected())
        {
            tcpSocket.write(cmd);
            tcpSocket.waitForBytesWritten(-1);
            tcpSocket.waitForReadyRead(-1);
            QByteArray rs=tcpSocket.readAll();
            tcpSocket.disconnectFromHost();

            uchar *pt=(uchar*)(rs.data())+9;
            uchar *rss=new uchar[2*registerNum];
            std::reverse_copy(pt,pt+2*registerNum,rss);
            short *rsss=(short*)rss;
            std::reverse_copy(rsss,rsss+registerNum,registerValue);
            delete rss;

            return true;
        }
        return false;
    }



    static void startserver(uint16_t portno, std::string &result)
    {
        URControlQTServer urcs(portno, 80000);
        result=urcs.response.constData();
    }

};

#endif // URCONTROLQT_HPP
